/**
 * Created by ancheel on 2016/10/14.
 */
'use strict';

import qs from 'qs'
import fetch from 'dva/fetch'

export default function callApi(url, data=null, method='GET', headers={}) {
    let finUrl = url;
    let option = {
        method,
        credentials: 'include',
        headers: Object.assign({},
            {'Content-Type': 'application/json', },
            headers
        )
    }


    if(data && method != 'GET') {
        option.body = JSON.stringify(data);
    } else if(data){

        finUrl = `${url}?${qs.stringify(data)}`
    }

    return fetch(finUrl, option)
      .then(res => {
          if (res.status == 204) {
              return {res, json: {status: 204}}
          }

          return res.json().then(json => ({res, json}))
      }).then(ret => {
          const res = ret.res;
          const json = ret.json;
          const status = res.status;
          const headers = res.headers;

          if(!res.ok) {
              return Promise.reject({status, headers, message: json.message})
          }

          return {status, headers, json}
      }).catch(error => {
        return {error}
      })
}
